import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { TakeAddress } from "@/type/TakeType";
import { deleteTakeAPI, fetchAddressAPI, fetchDefaultTakeIdAPI, settingDefaultTakeAPI } from "@/api/takeAddressAPI";
import { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";


type InitialState = {
   takeList: TakeAddress[],
   defaultId: number,
   isDefault: boolean,
}

const initialState: InitialState = {
   takeList: [],
   defaultId: 0,
   isDefault: false,
};

/**
 * @description 获取收货地址列表的AsyncThunk函数
 * */
export const fetchTakeListThunk: AsyncThunk<TakeAddress[], void, AsyncThunkConfig> = createAsyncThunk("fetchTakeListThunk", async (_, { rejectWithValue }) => {
   try {
      const { data: { list } } = await fetchAddressAPI();
      return list;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 获取默认收货地址id的AsyncThunk函数
 * */
export const fetchDefaultTakeIdThunk: AsyncThunk<number, void, AsyncThunkConfig> = createAsyncThunk("fetchDefaultTakeIdThunk", async (_, { rejectWithValue }) => {
   try {
      const { data } = await fetchDefaultTakeIdAPI();
      return data.defaultId;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 删除收货地址的AsyncThunk函数
 * */
export const deleteTakeThunk: AsyncThunk<string[], number, AsyncThunkConfig> = createAsyncThunk("deleteTakeThunk", async (addressId, { rejectWithValue }) => {
   try {
      const { data } = await deleteTakeAPI(addressId);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 设置默认地址的AsyncThunk函数
 * */
export const settingDefaultTakeThunk: AsyncThunk<"设置默认地址成功", number, AsyncThunkConfig> = createAsyncThunk("settingDefaultTakeThunk", async (addressId, { rejectWithValue }) => {
   try {
      await settingDefaultTakeAPI(addressId);
      return "设置默认地址成功";
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const takeStore = createSlice({
   name: "takeStore",
   initialState,
   reducers: {},
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchTakeListThunk.fulfilled, (state: InitialState, action: PayloadAction<TakeAddress[]>) => {
         state.takeList = action.payload;
      });
      builder.addCase(fetchDefaultTakeIdThunk.fulfilled, (state: InitialState, action: PayloadAction<number>) => {
         const isDefault = state.takeList.every(item => item.address_id === action.payload);
         state.isDefault = isDefault;
         state.defaultId = action.payload;
      });
   },
});

export default takeStore.reducer;
